const app = getApp()

import Dialog from '@vant/weapp/dialog/dialog';
import Notify from '@vant/weapp/notify/notify';

import {
    selfFormatTimeYMD,
    selfFormatTimeHM
} from "../../../../utils/util.js"

import {
    selectReservationListByUserIdRq,
    selectVisitorInvitationRecordRq,
    cancelOrderRq
} from "../../../../api/meeting/meetingRoom.js"

Page({

    /**
     * 页面的初始数据
     */
    data: {
        IMG_NAME: app.IMG_NAME,
        userData: null,
        dataChange: false,
        tabTitle: '预约记录',
        // 预约记录参数
        reservationPageNum: 1,
        reservationPageSize: 10,
        reservationDataList: [],
        reservationIsDataAll: false,
        // 参与记录参数
        participatePageNum: 1,
        participatePageSize: 10,
        participateDataList: [],
        participateIsDataAll: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let _this = this;
        _this.setData({
            userData: wx.getStorageSync('user'),
        })
        // 获取数据
        let userId = _this.data.userData.id
        // 获取预约数据
        _this.getReservationData({
            userId,
            pageNum: _this.data.reservationPageNum,
            pageSize: _this.data.reservationPageSize,
        })
        // 获取参与数据
        _this.getParticipateData({
            userId,
            pageNum: _this.data.participatePageNum,
            pageSize: _this.data.participatePageSize
        })
    },

    // 获取数据
    getDataList() {
        // 获取参数
        let _this = this;
        let tabTitle = _this.data.tabTitle
        let userId = _this.data.userData.id
        let isDataAll = null
        let pageNum = null
        let pageSize = null
        if (tabTitle == '预约记录') {
            // 预约记录参数
            isDataAll = _this.data.reservationIsDataAll
            pageNum = _this.data.reservationPageNum
            pageSize = _this.data.reservationPageSize

        } else if (tabTitle == '预约记录') {
            // 参与记录参数
            isDataAll = _this.data.participateIsDataAll
            pageNum = _this.data.participatePageNum
            pageSize = _this.data.participatePageSize
        } else {
            wx.showToast({
                title: `tab 切换错误(${tabTitle})`,
                icon: 'none',
            });
            return;
        }

        // 判断数据是否已全部加载
        if (isDataAll) {
            return;
        }
        // 传递参数
        let param = {
            userId,
            pageNum,
            pageSize
        }
        if (tabTitle == '预约记录') {
            // 获取预约数据
            _this.getReservationData(param)
        } else if (tabTitle == '预约记录') {
            // 获取参与数据
            _this.getParticipateData(param)
        }
    },

    // 获取预约数据
    getReservationData(param) {
        let _this = this;
        let {
            pageNum,
            pageSize,
            userId
        } = param
        // 查询数据
        selectReservationListByUserIdRq({
            pageNum,
            pageSize,
            userId
        }).then(res => {
            console.log('selectReservationListByUserIdRq', res);
            // 判断数据是否全部查询
            let queryDataList = res.page.records;
            if (queryDataList && queryDataList.length > 0) {
                // 更新参数
                let reservationDataList = _this.data.reservationDataList.concat(_this.formartData(queryDataList));
                let reservationPageNum = _this.data.reservationPageNum + 1;
                _this.setData({
                    reservationPageNum,
                    reservationDataList,
                })
            } else {
                _this.setData({
                    reservationIsDataAll: true
                })
            }
        })
    },

    // 获取参与数据
    getParticipateData(param) {
        let _this = this;
        let {
            pageNum,
            pageSize,
            userId
        } = param
        // 查询数据
        selectVisitorInvitationRecordRq({
            pageNum,
            pageSize,
            userId
        }).then(res => {
            console.log('selectVisitorInvitationRecordRq', res);
            // 判断数据是否全部查询
            let queryDataList = res.page.records;
            if (queryDataList && queryDataList.length > 0) {
                // 更新参数
                let participateDataList = _this.data.participateDataList.concat(_this.formartData(queryDataList));
                let participatePageNum = _this.data.participatePageNum + 1;
                _this.setData({
                    participatePageNum,
                    participateDataList,
                })
            } else {
                _this.setData({
                    participateIsDataAll: true
                })
            }
        })
    },

    // 格式化数据
    formartData(queryDataList) {
        // 格式化数据
        return queryDataList.map(item => {
            item.timeSlot = selfFormatTimeYMD(item.startTime) + ' ' + selfFormatTimeHM(item.startTime) + '~' + selfFormatTimeHM(item.endDate);
            // 状态字体颜色
            let statusColor = "#FFB119";
            // 按钮是否显示
            let statusValue = item.statusValue;
            let showPay = false;
            let showInvite = false;
            let showCancel = false;
            let showDetail = false;
            // 待支付 0 ：去支付、取消订单、查看详情
            if (statusValue == 0) {
                showPay = true;
                showCancel = true;
                showDetail = true;
                // 状态字体颜色
                statusColor = "#FFB119";
            }
            // 待使用 1：去邀请、取消订单、查看详情
            if (statusValue == 1) {
                showInvite = true;
                showCancel = true;
                showDetail = true;
                // 状态字体颜色
                statusColor = "#3794FF";
            }
            // 进行中 2：去邀请、查看详情
            if (statusValue == 2) {
                showInvite = true;
                showDetail = true;
                // 状态字体颜色
                statusColor = "#FF4040";
            }
            // 已结束 3：查看详情
            if (statusValue == 3) {
                showDetail = true;
                // 状态字体颜色
                statusColor = "#333333";
            }
            // 已取消 4：查看详情
            if (statusValue == 4) {
                showDetail = true;
                // 状态字体颜色
                statusColor = "#7F7F7F";
            }
            //
            // 赋值
            item.showPay = showPay;
            item.showInvite = showInvite;
            item.showCancel = showCancel;
            item.showDetail = showDetail;
            // 状态字体颜色
            item.statusColor = statusColor;
            // 图片
            if (item.roomContent.indoorPicUrl) {
                try {
                    item.roomContent.indoorPicUrlFirst = JSON.parse(item.roomContent.indoorPicUrl)[0].url
                } catch (error) {
                    console.log(`JSON error : ${error}`);
                }
            }
            return item;
        })

    },

    // 跳转-支付
    jumpPay(e) {
        console.log('jumpPay', e);
        wx.navigateTo({
            url: "/pages/meeting/pay/waitPay/waitPay?id=" + e.currentTarget.dataset.id + "&type=meetingRoom"
        })
    },

    // 跳转-预约详情
    jumpMeetingDetail(e) {
        console.log('jumpMeetingDetail', e);
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: "/pages/meeting/reservationRecord/meetingRecord/meetingDetail/meetingDetail?id=" + id,
        })
    },

    // 跳转-参与详情
    jumpParticipateDetail(e) {
        console.log('jumpParticipateDetail', e);
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: "/pages/meeting/invite/invite?id=" + id,
        })
    },

    // tab 点击切换
    tabClickSwitch(event) {
        console.log('tabClickSwitch', event);
        let _this = this;
        _this.setData({
            tabTitle: event.detail.title
        })
    },

    // 取消订单
    cancelOrder(e) {
        console.log('cancelOrder', e);
        let _this = this;
        let id = e.currentTarget.dataset.id
        const beforeClose = (action) => {
            console.log('action', action);
            return new Promise((resolve) => {
                if (action === 'confirm') {
                    cancelOrderRq({
                        id,
                        cancelResaon: ""
                    }).then(res => {
                        console.log('cancelOrderRq', res);
                        if (res.code == 0) {
                            // 刷新预约数据
                            _this.setData({
                                reservationPageNum: 1,
                                reservationDataList: [],
                                reservationIsDataAll: false,
                            })
                            _this.getDataList()
                        } else {
                            // 危险通知
                            Notify({
                                type: 'danger',
                                message: res.msg
                            });
                        }
                        resolve(true);
                    })
                } else {
                    // 拦截取消操作
                    resolve(true);
                }
            });
        }
        Dialog.confirm({
            title: '提示',
            message: '如需退款,请联系园区运营管理人员!',
            beforeClose,
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let _this = this;
        // 数据是否变化
        if (_this.data.dataChange) {
            // 刷新数据
            _this.setData({
                dataChange: false,
                // 预约记录参数
                reservationPageNum: 1,
                reservationDataList: [],
                reservationIsDataAll: false,
                // 参与记录参数
                participatePageNum: 1,
                participateDataList: [],
                participateIsDataAll: false,
            })

            // 获取数据
            let userId = _this.data.userData.id
            // 获取预约数据
            _this.getReservationData({
                userId,
                pageNum: _this.data.reservationPageNum,
                pageSize: _this.data.reservationPageSize,
            })
            // 获取参与数据
            _this.getParticipateData({
                userId,
                pageNum: _this.data.participatePageNum,
                pageSize: _this.data.participatePageSize
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        console.log('onPullDownRefresh', '页面相关事件处理函数--监听用户下拉动作');

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        console.log('onReachBottom', '页面上拉触底事件的处理函数');
        let _this = this;
        // 获取数据
        _this.getDataList()
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(e) {
        console.log('onShareAppMessage', e);
        let _this = this;
        let id = e.target.dataset.id;
        let detail = _this.data.reservationDataList.find(item => item.id == id)
        //
        let param = {
            title: detail.title,
            path: "/pages/meeting/invite/invite?id=" + id,
            imageUrl: app.IMG_NAME + detail.roomContent.indoorPicUrlFirst,
        }
        console.log('onShareAppMessage', param);
        return param;
    }
})